# coding: utf-8
from pathlib import Path
from edge_tts import Communicate, SubMaker, VoicesManager, list_voices, exceptions

from ..signal_bus import signalBus
from ..history import History


def tts_run_communicate(
        text: str,
        voice: str = 'en-US_MichaelVoice',
        rate: int = 0,
        volume: int = 0,
        pitch: int = 0,
        save_path: Path = None
):
    if rate >= 0:
        rate = f'+{rate}%'
    else:
        rate = f'{rate}%'
    if volume >= 0:
        volume = f'+{volume}%'
    else:
        volume = f'{volume}%'
    if pitch >= 0:
        pitch = f'+{pitch}Hz'
    else:
        pitch = f'{pitch}Hz'
    communicate = Communicate(
        text,
        voice,
        rate=rate,
        volume=volume,
        pitch=pitch,
    )
    sub_maker = SubMaker()
    with open(save_path, 'wb') as f:
        for chunk in communicate.stream_sync():
            if chunk["type"] == "audio":
                f.write(chunk["data"])
            elif chunk["type"] == "WordBoundary":
                sub_maker.feed(chunk)

    with open(save_path.with_suffix('.srt'), "w", encoding="utf-8") as f:
        f.write(sub_maker.get_srt())

    with open(save_path.with_suffix('.vtt'), "w", encoding="utf-8") as f:
        f.write('WEBVTT\n\n\n' + sub_maker.get_srt())

    save_path = save_path.as_posix()
    History().add(text, save_path)
    signalBus.reloadHistory.emit()
